package com.atguigu.tingshu.album.mq;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.sound.midi.Track;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class TrackReceiver {
    @Autowired
    private TrackInfoService trackInfoService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @KafkaListener(topics = KafkaConstant.QUEUE_TRACK_STAT_UPDATE)
    public void trackStatUpdate(ConsumerRecord<String,String> consumerRecord){
        String value = consumerRecord.value();
        if (!StringUtils.isEmpty(value)){
            TrackStatMqVo trackStatMqVo = JSON.parseObject(value, TrackStatMqVo.class);
            /**
             * 保证接口幂等性，使用Redis中的setnx命令
             */
            String businessNo = trackStatMqVo.getBusinessNo();
            String redisKey = "track:stat:update:"+businessNo;
            Boolean ifAbsent = redisTemplate.opsForValue().setIfAbsent(redisKey, businessNo, 1, TimeUnit.HOURS);
            if (ifAbsent){      //如果数据设置成功，说明消息第一次消费
                trackInfoService.updateTrackStat(trackStatMqVo);
                log.info("更新声音播放量成功了，data：{}", JSON.toJSONString(trackStatMqVo));
            }
        }

    }
}
